package main

import ("net/http"; "fmt"; "io")
import ("github.com/dchest/authcookie")

/*
   /login to login
   /whatever to do something while logged in
*/

var secret = []byte("inimitable depth")

func HelloServer(c http.ResponseWriter, req *http.Request) {
   cookie, err := req.Cookie( "session" )
   if err == nil {
       login := authcookie.Login( cookie.Value, secret )
       fmt.Println( "login:", login, "from:", cookie )
       if login == "" {
           fmt.Println( "Could not get login" )
           requestLogin( c, req )
       } else {
           io.WriteString( c, "You are logged in, " )
           io.WriteString( c, login )
           io.WriteString( c, ".\n" )
       }
   } else {
       fmt.Println( "OOPS:", err )
           requestLogin( c, req )
   }
}

func requestLogin( c http.ResponseWriter, req *http.Request ) {
   http.Redirect( c, req, "/login", 303 )
}

var loginPage = `
   <html>
   <head><title>Login</title></head>
   <body>
   <h1>Porcupine Login Page</h1>

   <form action="/authorise" method="POST">
       <div>Name: <input type="text" name="name" /></div>
       <div>Password: <input type="password" name="pwd" /></div>
       <input type="submit" value="Submit" />
   </form>

   </body>
   </html>
`

func LoginServer(c http.ResponseWriter, req *http.Request) {
   fmt.Println("Sending login page")
   io.WriteString( c, loginPage )
}

func Authorise( c http.ResponseWriter, req *http.Request ) {
   user := req.FormValue( "name" )
   password := req.FormValue( "pwd" )
   validated := user == "chris" && password == "SPOO"
   fmt.Println( ">> user:", user, "password:", password, "validated:", validated )
   if validated {
       cookie := authcookie.NewSinceNow( "user", 60*60*24, secret )
       fmt.Println("createdCookie:", cookie)
       http.SetCookie( c, &http.Cookie{Name: "session", Value: cookie} )
       http.Redirect( c, req, "/hello", 303 )
   } else {
       requestLogin( c, req )
   }
}

func main() {
	http.Handle( "/files/", http.StripPrefix( "/files", http.FileServer( http.Dir( "/tmp" ) ) ) )
   	http.Handle( "/hello", http.HandlerFunc( HelloServer ) )
   	http.Handle( "/login", http.HandlerFunc( LoginServer ) )
   	http.Handle( "/authorise", http.HandlerFunc( Authorise ) )
   	err := http.ListenAndServe(":8090", nil);
   	if err != nil { panic( "ListenAndServe: " + err.Error() ) }
}




